package com.jt.serviceImpl;

import com.jt.pojo.Item;
import com.jt.pojo.ItemDesc;
import com.jt.pojo.ItemParam;
import com.jt.service.ItemService;
import com.jt.util.HttpClientService;
import com.jt.utils.ObjectMapperUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author dc
 * @Classname ItemServiceImpl
 * @Date 2020/2/24 9:46
 */
@Service
public class ItemServiceImpl implements ItemService {


    @Autowired
    private HttpClientService httpClientService;


    @Override
    public Item findItemById(Long itemId) {
        String url="http://manage.jt.com/web/item/findItemById";
        Map<String,String> params = new HashMap<>();
        params.put("itemId",itemId+"");
        String itemJson = httpClientService.doGet(url, params);
        Item item = ObjectMapperUtil.toObject(itemJson, Item.class);
        return item;
    }


    @Override
    public ItemDesc findItemDescById(Long itemId) {
        String url="http://manage.jt.com/web/item/findItemDescById";
        Map<String,String> params = new HashMap<>();
        params.put("itemId",itemId+"");
        String itemJson = httpClientService.doGet(url, params);
        ItemDesc itemdesc = ObjectMapperUtil.toObject(itemJson, ItemDesc.class);
        return itemdesc;
    }

    @Override
    public String findItemParamById(Long itemId) {
        String url = "http://manage.jt.com/web/item/findItemParamById";
        Map<String,String> params = new HashMap<>();
        params.put("itemId",itemId+"");
        String itemJson = httpClientService.doGet(url, params);
        ItemParam itemParam=new ItemParam();
        StringBuffer sb=new StringBuffer();
        try {
            itemParam = ObjectMapperUtil.toObject(itemJson, ItemParam.class);
            String itemParams = itemParam.getItemParams();
            //将商品参数转化为map集合
            List<Map> jsonList = ObjectMapperUtil.toList(itemParams, Map.class);
            //生成html
            sb.append("<table cellpadding=\"0\" cellspacing=\"1\" width=\"100%\" border=\"0\" class=\"tb-void\">" );
            sb.append("	<tbody>");
            //拼接标题
            for(Map m1:jsonList){
                sb.append("<tr class=\"tr-td\">");
                sb.append("<th colspan=\"2\">"+m1.get("group")+"</th>");
                sb.append("	</tr>");
                List<Map> list2 = (List<Map>) m1.get("params");
                //拼接每个标题下的具体参数
                for(Map m2:list2){
                    sb.append("<tr>");
                    sb.append("<td>"+m2.get("k")+"</td>" );
                    sb.append("<td>"+m2.get("v")+"</td>" );
                    sb.append("</tr>" );
                }
            }
            sb.append("</tbody>" );
            sb.append("</table>");
        }catch (Exception e){
            return "";
        }
        return sb.toString();
    }
}
